﻿// JavaScript Document
$(function () {
    var txt = "";
    //editData($("#labelContent").val());
	//-------------------编辑(start)-------------------
    var topocontent = $('#topocontent'), lefticon = $('#lefticon');
	
	//自定义鼠标事件
	var rightkeyPop = $('#rightkeyPop'),
		relationWrap = $('#relationWrap'),
		relevanceBox = $('#relevanceBox'),
	    delEle = $('#delEle');
	
	$(document).on("contextmenu", function() { return false; }); 
	$(document).on('mousedown', '#topocontent div.elebox', function(event){
	    if (event.which == 3) {
	        txt = "";
		    var $this = $(this),
			    event = event || window.event,
			    oLeft = parseInt(event.clientX),
				oTop = parseInt(event.clientY),
				span = $this.children('span'),
				idStr = $this.attr('id');

		    rightkeyPop.find('input[type="checkbox"]').removeAttr("checked");
		    rightkeyPop.css({ left: oLeft, top: oTop, zIndex: 2999 }).attr('rightkey_click_id', idStr).show();
		}
	});
	$(document).on('mouseout', '#topocontent div.elebox', function(){
		rightkeyPop.hide();
	});
	$(document).on('mouseover', '#topocontent div.elebox', function(){
		return false;
	});
	$(document).on('click', '#delEle', function(){
		var idStr = rightkeyPop.attr('rightkey_click_id');

	    layer.msg("确认删除此元素？", {
	        time: 0,
	        btn: ['确定', '取消'],
	        yes: function (index) {
	            layer.close(index);
	            $("#" + idStr).remove();
	        }
	    });
	});

	
	$(document).on('click', '#relationWrap input[type="checkbox"]', function () {
	    $(this).attr("checked", true);
	    if ($(this).attr("checked")) {
	        if (txt == "") {
	            txt = "${" + $(this).val() + "}";
	        }
	        else {
	            txt += ",${" + $(this).val() + "}";
	        }
	    }
	    
	    var idStr = rightkeyPop.attr('rightkey_click_id');
		
	    if ($('#' + idStr).hasClass("uilabel")) {
	        $('#' + idStr).children("textarea").html(txt);
	    } else if ($('#' + idStr).hasClass("uibar") || $('#' + idStr).hasClass("uiqr")) {
	        $('#' + idStr).children('input[type="hidden"]').val(txt);
	    }
	});

	rightkeyPop.mouseover(function(){
		$(this).show();
		return false;
	});
	relevanceBox.hover(function(){
	    relationWrap.show();
	}, function(){
	    relationWrap.hide();
	});
	$('body').mouseover(function(){
	    rightkeyPop.hide();
	});
	
	//拖动创建元素
    lefticon.children('div.iconitems').draggable({
	    helper: 'clone',
	    scope: 'topo'
	});
	topocontent.droppable({
	    scope: 'topo',
		drop: function(event, ui){
			//获取基本元素与参数
			var $this = $(this),
				dragui = ui.draggable,
				fatop = parseInt($this.offset().top),
				faleft = parseInt($this.offset().left),
				uitop = parseInt(ui.offset.top),
				uileft = parseInt(ui.offset.left),
				imgsrc = dragui.children('img').attr('src'),
				spantxt = dragui.children('span').text(),
				uid = dragui.attr('icontype'),
				alluid = topocontent.children('div.' + uid);
			
			//ID计算
			var allicon = alluid.length,
				idnum = 0,
				idArr  = new Array;
			alluid.each(function(i) {
				idArr.push(parseInt($(this).attr('id').split('_')[1]));
			});
			idArr.sort(function(a,b){return a>b?1:-1});
			for(i = 0; i < allicon; i++){
			   var idArrOne = parseInt(idArr[i]);
				if(i != idArrOne){
					idnum = idArrOne - 1;
					break;
				}else{
					idnum = allicon;
				} 
			}
			
			//插入元素组织
		    var newstyle = 'left:' + (uileft - faleft) + 'px;top:' + (uitop - fatop) + 'px',
				newid = uid + '_' + idnum,
				newsrc = imgsrc.replace('little-icon', 'big-icon'),
				str = '<div class="elebox '+uid+'" id='+newid+' style='+newstyle+'><img src='+newsrc+'><input type="hidden"></div>';
			
		    if (uid == "uilabel") {
		        str = '<div class="elebox ' + uid + '" id=' + newid + ' style=' + newstyle + '><textarea style="resize:none;padding:0;min-height:0;float:none;"></textarea></div>';
		    }

			$this.append(str);
			$("#" + newid).resizable({ alsoResize: $("#" + newid).children().first() }).draggable({ containment: "parent" });
		}
	});
    //-------------------编辑(end)-------------------

    //-------------------保存(start)-------------------
	function saveCanvasData() {
	    //var blocks = [];
	    //$("#topocontent .elebox").each(function (idx, elem) {
	    //    var $elem = $(elem);
	    //    blocks.push({
	    //        BlockId: $elem.attr('id'),
	    //        BlockClass: $elem.attr('class').split(' ')[1],
	    //        BlockImg: $elem.children('img').attr('src'),
	    //        BlockText: $elem.children('span').text(),
	    //        BlockX: parseInt($elem.css("left")),
	    //        BlockY: parseInt($elem.css("top"))
	    //    });
	    //});
	    //serliza = JSON.stringify(connects) + "&" + JSON.stringify(blocks);
	    //return serliza;
	    return $("#topocontent").html();
	}
    //-------------------保存(end)-------------------
	
	//-------------------预览(start)-------------------
	var topoView = $('#topoView'),
	    viewTopoBtn = $('#viewTopoBtn');
	viewTopoBtn.click(function(){
	    $.iframePop('topo-view.html', 640, 900);
	});
	topoView.load('json/connection.json', function(response, status){
	    if(status == "success"){
			$.closePop('loadingPop');
			viewPop(response);
		}else{
		    $.popupEle('loadingPop');
		}
	});
	
	function viewPop(response){
	    var list = eval(response.split('&')[0]),
			blocks = eval(response.split('&')[1]),
			htmlText = "",
			conn = "";
		//------------插入元素-------------
		for( var i in blocks){
			var viewstyle = 'left:'+blocks[i].BlockX+'px;top:'+blocks[i].BlockY+'px;',
				viewid = blocks[i].BlockId,
				viewClass = blocks[i].BlockClass,
				viewsrc = blocks[i].BlockImg,
				viewTxt = blocks[i].BlockText;
			htmlText = htmlText + '<div class="elebox cursor_default '+viewClass+'" id='+viewid+' style='+viewstyle+'><img src='+viewsrc+'><span class="dragPoint cursor_default">'+viewTxt+'</span></div>';
		};
		topoView.html(htmlText);
		
		//------------更改样式-------------
		for( var i in list){
			var conor = instanceView.connect({ source: list[i].PageSourceId, target:list[i].PageTargetId});
			conor.getOverlay("label").setLabel(list[i].connectionLab);
			conor.setPaintStyle({fillStyle : list[i].lineColor, strokeStyle: list[i].lineColor});
		};
	}
	//-------------------预览(end)-------------------

    //-------------------表格(Start)-------------------
	var insertTable = function (btn, opt) {

	    if (!btn) { return; }

	    this.btn = btn;

	    opt = opt || {};

	    this.box = null;//弹框

	    this.inBox = null;

	    this.pickUnLight = null;

	    this.pickLight = null;

	    this.status = null;

	    this.minSize = opt.min || [5, 5];//最小列数和行数

	    this.maxSize = opt.max || [15, 15];//最大列数和行数

	    this.insert = opt.insert;//回调

	    this.nowSize = [];//当前选择尺寸

	    this.isInit = { create: false, bind: false };

	    this.bind();

	}

	insertTable.prototype = {

	    init: function () {

	        if (this.isInit.create) { return; }

	        this.isInit.create = true;

	        var id = 'in_tab_box_' + String(Math.ceil(Math.random() * 100000) + String(new Date().getTime())),

             html = '<div class="in_tab_box" id="' + id + '">';

	        html += '<div class="itb_con">';

	        html += '<div class="itb_picker_unlight"></div>';

	        html += '<div class="itb_picker_light"></div>';

	        html += '</div>';

	        html += '<div class="itb_picker_status"></div>';

	        html += '</div>';

	        $("#lefticon").append(html);

	        this.box = $("#" + id);

	        this.inBox = this.box.find(".itb_con");

	        this.pickAll = this.box.find(".itb_picker_all");

	        this.pickUnLight = this.box.find(".itb_picker_unlight");

	        this.pickLight = this.box.find(".itb_picker_light");

	        this.status = this.box.find(".itb_picker_status");



	        this.setBg(this.minSize[0], 0);

	        this.setBg(this.minSize[1], 1);



	        this.status.text(0 + '列 x ' + 0 + '行');

	    },

	    bind: function () {

	        var T = this,

             pos,//弹框显示位置

             m,

             bPos,//弹框可选区域位置

             mPos;//鼠标位置

	        this.btn.mouseover(function () {

	            if (!T.isInit.create) { T.init(); }//初始化弹框

	            if (!T.isInit.bind) { B(); }//初始化事件

	            m = $(this);

	            if (T.box.is(":hidden")) {

	                pos = {

	                    top: m.offset().top + 30,

	                    left: m.offset().left+30
	                }

	                T.box.css({

	                    "top": pos.top,

	                    "left": pos.left

	                }).fadeIn(100);

	                bPos = {

	                    top: T.inBox.offset().top,

	                    left: T.inBox.offset().left

	                }

	                $(document).bind("click", function () { T.hide(); });

	            } else {

	                T.hide();

	            }

	            return false;

	        })

	        function B() {

	            T.isInit.bind = true;

	            T.inBox.mousemove(function (e) {

	                mPos = {

	                    x: e.clientX,

	                    y: e.clientY

	                }

	                if (mPos.x < bPos.left || mPos.y < bPos.top) { return; }

	                T.nowSize[0] = Math.ceil((mPos.x - bPos.left) / 18);//列数

	                T.nowSize[1] = Math.ceil((mPos.y - bPos.top) / 18);//行数



	                if (T.nowSize[0] >= T.minSize[0] && T.nowSize[0] < T.maxSize[0]) {

	                    T.setBg(T.nowSize[0] + 1, 0);

	                } else if (T.nowSize[0] < T.minSize[0]) {

	                    T.setBg(T.minSize[0], 0);

	                } else {

	                    T.nowSize[0] = T.maxSize[0];

	                }

	                if (T.nowSize[1] >= T.minSize[1] && T.nowSize[1] < T.maxSize[1]) {

	                    T.setBg(T.nowSize[1] + 1, 1);

	                } else if (T.nowSize[1] < T.minSize[1]) {

	                    T.setBg(T.minSize[1], 1);

	                } else {

	                    T.nowSize[1] = T.maxSize[1];

	                }



	                T.pickLight.css({

	                    "width": T.nowSize[0] + 'em',

	                    "height": T.nowSize[1] + 'em'

	                })

	                T.status.text(T.nowSize[0] + '列 x ' + T.nowSize[1] + '行');

	            })

	            //单击确认插入表格

	            T.box.click(function () {

	                if (T.nowSize[0] > 0 && T.nowSize[0] <= T.maxSize[0] && T.nowSize[1] > 0 && T.nowSize[1] <= T.maxSize[1]) {

	                    var rows = T.nowSize[1],

                         cols = T.nowSize[0];

	                    try { T.insert(rows, cols); } catch (e) { }

	                }

	            })

	        }

	    },

	    //调整背景区域

	    setBg: function (size, t) {

	        if (t == 0) {

	            this.inBox.width(size + 'em');

	            this.pickUnLight.width(size + 'em');

	        } else {

	            this.inBox.height(size + 'em');

	            this.pickUnLight.height(size + 'em');

	        }

	    },

	    //隐藏弹框

	    hide: function () {

	        var T = this;

	        this.box.fadeOut(100, function () {

	            //重置

	            T.setBg(T.minSize[0], 0);

	            T.setBg(T.minSize[1], 1);

	            T.pickLight.css({

	                "width": '0',

	                "height": '0'

	            })

	        });

	    }

	}

	new insertTable($(".tableitems"), {

	    min: [4, 4],

	    max: [20, 20],

	    insert: function (rows, cols) {

	        //这里只返回所选行数rows和列数cols,插入后的效果和样式需自定义,以下只是做简单的示例

	        //alert('插入了一个'+rows+'行'+cols+'列的表格');

	        var allui = topocontent.children('div.uitable');
	        var allicon = allui.length,
				idnum = 0,
				idArr = new Array;
	        allui.each(function (i) {
	            idArr.push(parseInt($(this).attr('id').split('_')[1]));
	        });
	        idArr.sort(function (a, b) { return a > b ? 1 : -1 });
	        for (i = 0; i < allicon; i++) {
	            var idArrOne = parseInt(idArr[i]);
	            if (i != idArrOne) {
	                idnum = idArrOne - 1;
	                break;
	            } else {
	                idnum = allicon;
	            }
	        }

	        var id_new = "uitable_" + idnum;

	        var html = '<div class="elebox uitable" id="' + id_new + '"><table>';

	        for (var i = 0; i < rows; i++) {

	            html += '<tr>';

	            for (var j = 0; j < cols; j++) {

	                html += '<td></td>';

	            }

	            html += '</tr>';

	        }

	        html += '</table></div>';

	        $("#topocontent").append(html);

	        $("#" + id_new).resizable({ alsoResize: $("#" + id_new).children().first() }).draggable({ containment: "parent" });
	    }
	});

	$(document).on("click", "#topocontent table td", function () {
	    //获得当前点击的对象
	    var td = $(this);
	    td.width(td.width());
	    td.height(td.height());
	    //取出当前td的文本内容保存起来
	    var oldText = td.text();
	    //建立一个文本框，设置文本框的值为保存的值
	    var input = $("<input type='text' value='" + oldText + "'/>");
	    //设置文本框的样式
	    input.css("border-width", "0");
	    input.css("font-size", "14px");
	    input.css("text-align", "left");
	    //设置文本框宽度等于td的宽度
	    input.width(td.width());
	    //将当前td对象内容设置为input
	    td.html(input);
	    //设置文本框的点击事件失效
	    input.click(function() {
	        return false;
	    });
	    
	    //当文本框得到焦点时触发全选事件
	    input.trigger("focus").trigger("select");
	    //当文本框失去焦点时重新变为文本
	    input.blur(function() {
	        var input_blur = $(this);
	        //保存当前文本框的内容
	        var newText = input_blur.val();
	        td.html(newText);
	    });
	    //响应键盘事件
	    input.keyup(function(event) {
	        // 获取键值
	        var keyEvent = event || window.event;
	        var key = keyEvent.keyCode;
	        //获得当前对象
	        var input_blur = $(this);
	        switch (key)
	        {
	            case 13://按下回车键，保存当前文本框的内容
	                var newText = input_blur.val();
	                td.html(newText);
	                break;

	            case 27://按下 esc键，取消修改，把文本框变成文本
	                td.html(oldText);
	                break;
	        }
	    });
	});
    //-------------------表格(End)-------------------
    
    //-------------------图片(Start)------------------
	$("#img_upload").change(function () {
	    //$("#imgUpload").val($(this).val());
	    if (typeof FileReader === 'undefined') {
	        $.alert("浏览器不支持本地预览");
	    } else {
	        var file = this.files[0];
	        if (!/image\/\w+/.test(file.type)) {
	            $.alert("请确保文件为图像类型");
	            return false;
	        }
	        var reader = new FileReader();
	        reader.readAsDataURL(file);
	        reader.onload = function (e) {
	            var allui = topocontent.children('div.uiimage');
	            var allicon = allui.length,
                    idnum = 0,
                    idArr = new Array;
	            allui.each(function (i) {
	                idArr.push(parseInt($(this).attr('id').split('_')[1]));
	            });
	            idArr.sort(function (a, b) { return a > b ? 1 : -1 });
	            for (i = 0; i < allicon; i++) {
	                var idArrOne = parseInt(idArr[i]);
	                if (i != idArrOne) {
	                    idnum = idArrOne - 1;
	                    break;
	                } else {
	                    idnum = allicon;
	                }
	            }

	            var imgid = "uiimage_" + idnum;
	            var imgHtml = '<div class="elebox uiimage" id=' + imgid + '><image src="' + this.result + '" /></div>';

	            var file = $("#img_upload");
	            var ie = (navigator.appVersion.indexOf("MSIE") != -1);
	            if (ie) {
	                var file2 = file.cloneNode(false);
	                file2.onchange = file.onchange;
	                file.parentNode.replaceChild(file2, file);
	            } else {
	                $(file).val("");
	            }

	            $("#topocontent").append(imgHtml);

	            $("#" + imgid).resizable({ alsoResize: $("#" + imgid).children().first() }).draggable({ containment: "parent" });
	        }
	    }
	});

    //-------------------图片(End)------------------
});


